﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using WindowsFormsApplication3.Conexion;
using WindowsFormsApplication3.Clases;

namespace WindowsFormsApplication3
{
    public partial class login : Form
    {
        //public static string vendedor;
        public static string variable;
        GestionManager ges = new GestionManager();
        public login()
        {
            InitializeComponent();
        }

        private bool comprobarVendedor(Usuario user)
        {

            Conexion.Conexion conn = new Conexion.Conexion();
            conn.conectar();
            if (string.IsNullOrWhiteSpace(txtrutlogin.Text) || string.IsNullOrWhiteSpace(txtpasslogin.Text))
            {
                MessageBox.Show("¡Faltan datos!", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                string sql = "SELECT rutcajero, contraseña FROM cajero where rutcajero = '" + user.rut_user + "' AND contraseña = '" + user.contrasena + "' AND estado='Activo'";
                try
                {
                    SqlCommand cmd = new SqlCommand(sql, conn.conector);
                    cmd.ExecuteNonQuery();
                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.Read())
                    {
                        //abrir menu vendedor
                        menuVendedor menuvnd = new menuVendedor();
                        menuvnd.Show();
                        GestionFgut g = new GestionFgut();
                       // vendedor = g.recuperarNombreSesionCajero(login.variable) + " " + g.recuperarApellidoSesionCajero(login.variable);
                        MessageBox.Show("Ha iniciado sesión como Vendedor.", "Bienvenido", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show("Intente nuevamente, usuario y/o contraseña no válida", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        LimpiarCampos();
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Error al intentar conectar con SQL Server:\n" + ex, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }


            }
            return true;
        }

        private void btentrar_Click(object sender, EventArgs e)
        {
            txtrutlogin.Text = Regex.Replace(txtrutlogin.Text.Trim(), @"\s+", " ");
            txtpasslogin.Text = Regex.Replace(txtpasslogin.Text.Trim(), @"\s+", " ");
            Usuario user = new Usuario();
            string rutcompleto = txtrutlogin.Text + "-" + txtdvlogin.Text;
            user.rut_user = rutcompleto;
            user.contrasena = txtpasslogin.Text;
            Conexion.Conexion conn = new Conexion.Conexion();
            variable = rutcompleto;
            conn.conectar();
            if (string.IsNullOrWhiteSpace(txtrutlogin.Text) || string.IsNullOrWhiteSpace(txtpasslogin.Text))
            {
                MessageBox.Show("¡Faltan datos!", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LimpiarCampos();
            }
            else
            {
                string sql = "SELECT rutadmin, contraseña FROM administrador where rutadmin = '" + user.rut_user + "' AND contraseña = '" + user.contrasena + "' AND estado='Activo'";
                try
                {
                    SqlCommand cmd = new SqlCommand(sql, conn.conector);
                    cmd.ExecuteNonQuery();
                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.Read())
                    {
                        //abrir menu administrador
                        menuAdministrador menuad = new menuAdministrador();
                        menuad.Show();
                        MessageBox.Show("Ha iniciado sesión como Administrador.","Bienvenido",MessageBoxButtons.OK,MessageBoxIcon.Information);

                        this.Hide();
                    }
                    else
                    {
                        //abrir menu administrador
                        comprobarVendedor(user);
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Error al intentar conectar con SQL Server:\n" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

        }

        private void LimpiarCampos()
        {
            txtrutlogin.Text = "";
            txtpasslogin.Text = "";
            txtdvlogin.Text = "";
        }

        private void btsalir_Click(object sender, EventArgs e)
        {
            DialogResult boton = MessageBox.Show("¿Está seguro que desea salir?", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
            if (boton == DialogResult.Yes)
            {
                Application.Exit();
            }
            else
            {
            }
        }

        private void txtrutlogin_TextChanged(object sender, EventArgs e)
        {
            if (txtrutlogin.Text == "")
            {
                txtdvlogin.Text = "";
            }
            if (txtrutlogin.TextLength == 7 || txtrutlogin.TextLength == 8)
            {
                int rut = Convert.ToInt32(txtrutlogin.Text);
                string digito = ges.digitoVerificador(rut);
                txtdvlogin.Text = digito;
            }
        }

        private void txtrutlogin_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsSeparator(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
            if (e.KeyChar == (char)Keys.Space)
            {
                e.Handled = true;
            }
        }

        private void txtpasslogin_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar) && !char.IsSeparator(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
            if (e.KeyChar == (char)Keys.Space)
            {
                e.Handled = true;
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void login_Load(object sender, EventArgs e)
        {
            txtrutlogin.Focus();
        }



    }
}
